package com.ksyun.ks3.services;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import okhttp3.Authenticator;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
import okhttp3.logging.HttpLoggingInterceptor;

public class OkHttpClientFactory {
    private static OkHttpClient instance;

    private OkHttpClientFactory() {
    }

    static OkHttpClient getInstance() {
        if (instance == null) {
            instance = new OkHttpClient.Builder().build();
        }
        return instance;
    }

    static OkHttpClient getInstance(final Ks3ClientConfiguration configuration) {
        if (instance == null) {
            // 设置重连次数
            OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    .connectTimeout(configuration.getConnectionTimeout(), TimeUnit.MILLISECONDS)
                    .readTimeout(configuration.getSocketTimeout(), TimeUnit.MILLISECONDS)
                    .writeTimeout(configuration.getSocketTimeout(), TimeUnit.MILLISECONDS)
                    .retryOnConnectionFailure(configuration.isRetryOnConnectionFailure());

            // 添加调试日志
            if (configuration.isEnableLog()) {
                HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
                interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                builder.addInterceptor(interceptor);
            }

            if (configuration.getProxyUsername() != null && configuration.getProxyPort() > 0) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP,
                        new InetSocketAddress(configuration.getProxyHost(), configuration.getProxyPort()));
                Authenticator proxyAuthenticator = new Authenticator() {
                    @Override
                    public Request authenticate(Route route, Response response) throws IOException {
                        String credentials = Credentials.basic(configuration.getProxyUsername(), configuration.getProxyPassword());
                        return response.request()
                                .newBuilder()
                                .header("Proxy-Authorization", credentials)
                                .build();
                    }
                };
                builder.proxy(proxy)
                        .proxyAuthenticator(proxyAuthenticator)
                        .authenticator(proxyAuthenticator);
            }

            instance = builder.build();
        }
        return instance;
    }

    private static ExecutorService getDefaultThreadPool() {
        return Executors.newCachedThreadPool();
    }
}
